//
//  MTVideoInfoController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/6.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory

/// 键盘
import IQKeyboardManagerSwift

/// 网络

import Moya
import Result
import RxSwift
import RxCocoa
/// nav
import YPNavigationBarTransition
class MTVideoInfoController: BaseViewController {
    /// MTProvider
    private lazy var upload_provider: MTProvider<UploadApi> = {
        return MTProvider<UploadApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    private lazy var user_provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    
    /// 上传回调
    typealias UploadSuccessHandler = (_: Bool) -> Swift.Void
    
    lazy var tableView: MTVideoInfoTableView = {
        let tv = MTVideoInfoTableView(frame: self.view.bounds)
        tv.verificationTask = self
        return tv
    }()
    
    private var selfVideoUrl: String?
    
    private var authVideoUrl: String?
    
    deinit {
        removeNotifications()
    }
    
}

// MARK: ------------------ Override ----------------------
extension MTVideoInfoController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addNotifications()
        initializeUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enableAutoToolbar = false
        IQKeyboardManager.shared.enable = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
//        if let a = alertView {
//            a.dismiss()
//            self.alertView = nil
//        }
    }
    
    
    
}

// MARK: ------------------ 初始化 ----------------------
extension MTVideoInfoController {
    
    private func initializeUI() {
        navigationItem.title = "上传视频"
        view.addSubview(tableView)
    }
    
}

// MARK: ------------------ 初始认证代理回调 MTInfoVideoTableViewVerificationTask ----------------------
extension MTVideoInfoController: MTInfoVideoTableViewVerificationTask {
    func infoVideoTableView() {
        uploadInitializeUserInfos()
    }
    
    private func uploadInitializeUserInfos() {
        
        let params: [String: Any] = ["url"    : authVideoUrl ?? "",
                                     "selfUrl"      : selfVideoUrl ?? "",]
        
        user_provider.originRequest(.femaleVideoValidation(params), callbackQueue: .global(), progress: nil) { [weak self] (result, _) in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async {
//                weakSelf.alertView?.dismiss()
            }
            switch result {
            case .success(let response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    
                    if code == 200, let result = datas["result"] as? [String: Any] {
                        /// 刷新用户模型
//                        UserCenter.default.set(with: result)
                        DispatchQueue.main.async {
                            UserStatusNavigate.push(from: weakSelf, withUserStatus: 12)
                        }
                    } else {
                        AlertManager.presentAlertView(message: datas["message"] as! String)
                    }
                    
                }
                break
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }
        
        
    }
    
}

// MARK: ------------------ 通知相关 ----------------------
extension MTVideoInfoController {
    
    private func addNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(shouldPushAuthVideo), name: GlobalNotificationName.authVideo.name, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(shouldPresentPhotoLibrary), name: GlobalNotificationName.presentPhotoLibrary.name, object: nil)
    }

    private func removeNotifications() {
//        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.authVideo.name, object: nil)
        NotificationCenter.default.removeObserver(self)
    }
    
}

// MARK: ------------------ 事件方法 ----------------------
@objc
extension MTVideoInfoController {
    
    private func shouldPushAuthVideo() {
        // 跳转去上传视频页
        let c = MTVideoVerificationViewController()
        c.completionHandler = { [weak self] (url, thumb) -> () in
            guard let weakself = self else { return }
            weakself.tableView.authVideoCover = thumb
            weakself.authVideoUrl = url
        }
        navigationController?.pushViewController(c, animated: true)
    }
    
    private func shouldPresentPhotoLibrary() {
        let c = PhotoLibraryViewController()
        c.delegate = self
        c.allowVideoSelection = true
        c.isOnlyVideo = true
        c.maxSelectdCount = 1
        let nav = BaseNavController(rootViewController: c)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true, completion: nil)
    }
}

// MARK: ------------------ PhotoLibraryViewControllerDelegate ----------------------
extension MTVideoInfoController: PhotoLibraryViewControllerDelegate {
    
    func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetWith asset: MTAsset) {
        if let model = UserMediaListModel(JSON: ["localAsset": asset,
                                                 "objType": asset.mediaType == .video ? 1 : 0]) {
            model.uploadStatus = .ready
            upload(model: model, currentIdx: -1) { (flag) in
                debugPrint(flag)
            }
            //            tableView.imageAsset = asset
        }
//        tableView.videoPath = asset.videoPath
//        upload(path: asset.videoPath ?? "")
    }
    
}

extension MTVideoInfoController {
    
        /// 上传模型
        private func upload(model: UserMediaListModel, currentIdx: Int, successHandler: @escaping UploadSuccessHandler) {
            if model.uploadStatus != .ready { return }
            guard let asset = model.localAsset else { return }
            
            if asset.mediaType == .video {
                var coverImage: UIImage?
                var videoPath: String?
                let group = DispatchGroup()
                var progressGroup = [Double](repeating: 0, count: 2)
                /// 获取封面图
                group.enter()
                MTAssetLibrary.default.requestImage(withAsset: asset.asset, photoWidth: ScreenWidth, progressHandler: { [weak self] (progress) in
                    guard let weakself = self else { return }
                    DispatchQueue.main.async {
                        if model.uploadStatus != .ready {
                            model.uploadStatus = .ready
                        }
                        progressGroup[0] = progress
//                        model.uploadProgress = weakself.calculateProgress(group: progressGroup, percentage: 0.1, doneProgress: 0)
    //                    weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                    }
                }, errorHandler: nil) { [weak self] (image, info, isDegraded) in
                    guard let weakself = self else { return }
                    if isDegraded == false, let image = image {
                        coverImage = image
                        weakself.tableView.selfCoverImage = image
                        group.leave()
                    }
                }
                /// 获取视频
                group.enter()
                MTAssetLibrary.default.requestVideo(withAsset: asset.asset, progressHandler: nil, errorHandler: nil, assetCompletion: nil) { [weak self] (progress, path) in
                    guard let weakself = self else { return }
                    DispatchQueue.main.async {
                        if progress > 0 {
                            if model.uploadStatus != .ready {
                                model.uploadStatus = .ready
                            }
                            progressGroup[1] = Double(progress)
//                            model.uploadProgress = weakself.calculateProgress(group: progressGroup, percentage: 0.1, doneProgress: 0)
    //                        weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                        }
                    }
                    if let path = path {
                        videoPath = path
                        group.leave()
                    }
                }
                
                group.notify(queue: .global()) {
                    if let videoPath = videoPath, let coverImage = coverImage {
                        self.uploadVideo(videoPath: videoPath, coverImage: coverImage, model: model, asset: asset, currentIdx: currentIdx, successHandler: successHandler)
                    }
                }
                
            } else {
                /// 图片上传
//                MTAssetLibrary.default.requestImage(withAsset: asset.asset, photoWidth: ScreenWidth, progressHandler: { [weak self] (progress) in
//                    guard let weakself = self else { return }
//                    DispatchQueue.main.async {
//                        if model.uploadStatus != .ready {
//                            model.uploadStatus = .ready
//                        }
////                        model.uploadProgress = weakself.calculateProgress(group: [progress], percentage: 0.1, doneProgress: 0)
//    //                    weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
//                    }
//                }, errorHandler: nil) { [weak self] (image, info, isDegraded) in
//                    guard let weakself = self else { return }
//                    if isDegraded == false, let image = image {
////                        weakself.upload(image: image, model: model, asset: asset, currentIdx: currentIdx, successHandler: successHandler)
//                    }
//                }
            }
            
        }
        
        /// 上传视频及封面图
        private func uploadVideo(videoPath: String, coverImage: UIImage, model: UserMediaListModel, asset: MTAsset, currentIdx: Int, successHandler: @escaping UploadSuccessHandler) {
            let group = DispatchGroup()
            var progressGroup = [Double](repeating: 0, count: 2)
            group.enter()
//            upload_provider.originRequest(.upload(coverImage), callbackQueue: .global(), progress: { [weak self] (progressResonpse) in
//                guard let weakself = self else { return }
//                DispatchQueue.main.async {
//                    if model.uploadStatus != .uploading {
//                       model.uploadStatus = .uploading
//                    }
//                    progressGroup[0] = progressResonpse.progress
////                    model.uploadProgress = weakself.calculateProgress(group: progressGroup, percentage: 0.89, doneProgress: 0)
//    //                weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
//                }
//            }) { [weak self] (result, _) in
//                guard let weakself = self else { return }
//                switch result {
//                case let .success(response):
//                    if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
//                        if code == 200, let url = datas["result"] as? String {
//                            DispatchQueue.main.async {
//                                model.coverImg = url
//                                group.leave()
//                            }
//                        } else {
//                            DispatchQueue.main.async {
//                                model.uploadStatus = .fail
//    //                            weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
//                            }
//                        }
//                    }
//                    break
//
//                case .failure(_):
//                    break
//                }
//            }
            
            group.enter()
            upload_provider.originRequest(.uploadVideo(URL(fileURLWithPath: videoPath)), callbackQueue: .global(), progress: { [weak self] (progressResponse) in
                guard let weakself = self else { return }
                DispatchQueue.main.async {
                    if model.uploadStatus != .uploading {
                       model.uploadStatus = .uploading
                    }
                    progressGroup[1] = progressResponse.progress
//                    model.uploadProgress = weakself.calculateProgress(group: progressGroup, percentage: 0.89, doneProgress: 0)
    //                weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                }
            }) { [weak self] (result, _) in
                guard let weakself = self else { return }
                switch result {
                case let .success(response):
                    if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                        if code == 200, let url = datas["result"] as? String {
                            DispatchQueue.main.async {
                                weakself.selfVideoUrl = url
                                model.href = url
                                group.leave()
                            }
                        } else {
                            DispatchQueue.main.async {
                                model.uploadStatus = .fail
    //                            weakself.tableView.refreshGalleryCollectionView(withIdx: currentIdx)
                            }
                        }
                    }
                    break
                    
                case .failure(_):
                    break
                }
            }
            
            group.notify(queue: .main) {
//                self.save(withModel: model, currentIdx: currentIdx, successHandler: successHandler)
            }
        }
    /// 上传视频
//    private func upload(path: String) {
//        let a = AlertManager.presentAlertView(message: "正在上传", autoPresent: false)
//        a.isBackgroundCoverEnabled = true
//        a.backgroundCoverBackgroundColor = UIColor.black.withAlphaComponent(0.5)
//        a.isBackgroundCoverViewGestureEnabled = false
//        a.shouldAutoDismiss = false
//        a.isDismissButtonHidden = true
////        self.alertView = a
//        a.present()
//
//        provider.originRequest(.uploadVideo(URL(fileURLWithPath: path)), callbackQueue: nil, progress: { (progressResponse) in
//            DispatchQueue.main.async {
//                a.message = String(format: "%.1f", progressResponse.progress * 100)
//            }
//        }) { [weak self] (result, _) in
//            a.dismiss()
//            guard let weakSelf = self else { return }
////            weakSelf.alertView = nil
//            switch result {
//            case let .success(response):
//                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
//                    if code == 200, let videoUrl = datas["result"] as? String {
////                        weakSelf.validateVideo(url: videoUrl)
//                    } else {
//                        AlertManager.presentAlertView(message: "视频上传失败")
//                    }
//                }
//                break
//
//            case let .failure(error):
//                AlertManager.presentAlertView(message: error.localizedDescription)
//                break
//            }
//        }
//
//    }
}


